<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/14
 * Time: 15:22
 */

namespace app\mec\controller;


use think\Db;
use think\Exception;
use think\Request;
use app\mec\model\UUser as UUserModel;//用户
use app\mec\model\Mechanism as MechanismModel;//机构

class Uuser extends Base
{
    /**
     * 机构志愿者列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $where = [];
            if(isset($params['key']) && $params['key'] != ''){
                $where['uuu.user_username|uuu.user_phone'] = ['like', "%" . $params['key'] . "%"];
            }
            $where['uuu.user_to_mechanism_id'] = ['=', session('mmid')];
            $page = input('page') ? input('page') : 1;
            $limits = input('limit') ? input('limit') : 10;// 获取总条数;
            $field = 'uuu.is_zyx,uuu.user_id, uuu.user_phone, uuu.user_username, uuu.user_attestation, uuu.user_me_content, 
            uuu.user_number, uuu.last_login_time, uuu.user_status, uuu.user_to_mechanism_id, um.mechanism_name';
            $uUserModel = new UUserModel();
            $lists = $uUserModel->getUserLists($field, $where, $page, $limits);
            $count = $uUserModel->countNum($where);
            foreach($lists as $key=>&$list){
                //最后登录时间
                if(!empty($list['last_login_time'])){
                    $list['last_login_time'] = date('Y-m-d H:i', $list['last_login_time']);
                }else{
                    $list['last_login_time'] = '';
                }
                //志愿者编码
                if(empty($list['user_number'])){
                    $list['user_number'] = '暂未认证成功';
                }else{
                    $list['user_number'] = trim($list['user_number'], ',');
                }
                //机构
                if($list['user_to_mechanism_id'] == -1){
                    $list['mechanism_name'] = '未加入机构';
                }
            }
            return json(['code'=>0,'msg'=>'','count'=>$count,'data'=>$lists]);
        }
        if(session('?uuuu_user_id')){
            session('uuuu_user_id',null);
        }
        return $this->fetch("uuser/index");
    }
    
    /**
     * 添加用户
     * @return mixed|\think\response\Json
     */
//    public function uUserAdd(){
//        if(Request::instance()->isAjax()){
//            $params = input('param.');
//            $uUserModel = new UUserModel();
//            $mechanismModel = new MechanismModel();
//            $phone = Db::table('up_u_user')->where('user_phone', $params['user_phone'])->find();
//            if($phone){
//                return json(['code' => 100, 'data' => '', 'msg' => '该手机号已被注册']);
//            }
//            if($params['user_attestation'] == 1){//未认证，则mechanism_id为-1
//                $params['mechanism_id'] = -1;
//                $params['user_number'] = '';
//            }else{//已认证，这需要志愿者编号
//                $num = $uUserModel->getMaxNum($params['mechanism_id']);
//                $res = $mechanismModel->getMechanismCode($params['mechanism_id']);
//                $mechanism_code = trim($res['mechanism_code'], ',');
//                if(!$num){//该机构暂无志愿者
//                    $num = ',' . $mechanism_code . '00001' . ',';
//                }else{
//                    $num = trim($num, ',') + 1;
//                    $leng = strlen($num);
//                    $totalLeng = '';
//                    if($res['mechanism_type'] == 1){
//                        $totalLeng = 8;
//                    }elseif($res['mechanism_type'] == 2){
//                        $totalLeng = 11;
//                    }elseif($res['mechanism_type'] == 3){
//                        $totalLeng = 14;
//                    }elseif($res['mechanism_type'] == 4){
//                        $totalLeng = 17;
//                    }elseif($res['mechanism_type'] == 5){
//                        $totalLeng = 20;
//                    }
//                    $zero = '';
//                    if($leng < $totalLeng){
//                        for($i=$leng; $i<$totalLeng; $i++){
//                            $zero .= '0';
//                        }
//                    }
//                    $num = ',' . $zero . $num . ',';
//                }
//            }
//            //志愿者编号
//            $data = [
//                'user_username' => $params['user_username'],
//                'user_phone' => $params['user_phone'],
//                'user_password' => md5($params['user_password']),
//                'user_attestation' => $params['user_attestation'],
//                'user_to_mechanism_id' => $params['mechanism_id'],
//                'user_number' => $num,
//                'user_time' => date('Y-m-d H:i:s'),//注册时间
//            ];
//            $res = $uUserModel->insertUser($data);
//            if($res){
//                return json(['code' => 200, 'data' => '', 'msg' => '注册成功']);
//            }else{
//                return json(['code' => 100, 'data' => '', 'msg' => '注册失败']);
//            }
//        }
//        $mechanismModel = new MechanismModel();
//        $mechanismInfo = $mechanismModel->getMechanismInfo();
//        $mechanismInfo = getCate($mechanismInfo);
//        $this->assign('mechanismInfo', $mechanismInfo);
//        return $this->fetch('uuser/uuseradd');
//    }
    
    /**
     * 修改志愿者编号
     * 可选择的机构为无下级机构、无机构志愿者、已认证、除总队以外的机构
     * @return mixed|\think\response\Json
     */
//    public function editUserCode(){
//        $uUserModel = new UUserModel();
//        if(Request::instance()->isAjax()){
//            $params = input('param.');
//            $params['mechanism_id'] = explode('&', $params['mechanism_id']);
//            $new_code = ',' . $params['mechanism_id'][1] . $params['new_code'] . ',';
//            $data = [
//                'user_to_mechanism_id' =>$params['mechanism_id'][0],
//                'user_number' => $new_code
//            ];
//            $res = $uUserModel->updateCode($params['id'], $data);
//            if($res){
//                return json(['code' => 200, 'data' => '', 'msg' => '修改成功']);
//            }else{
//                return json(['code' => 100, 'data' => '', 'msg' => '修改失败']);
//            }
//        }
//        $id = input('id');
//        $mechanismModel = new MechanismModel();
//        $lists = $mechanismModel->getNoSonMechanism();//获取所有无下级机构的机构
//        foreach($lists as $key=>&$list){
//            $res = Db::table('up_u_user')->where('user_to_mechanism_id', $list['mechanism_id'])->count();
//            if($res != 0){//去掉有机构志愿者的机构
//                unset($lists[$key]);
//            }
//            $list['mechanism_code'] = trim($list['mechanism_code'], ',');
//        }
//        $code = $uUserModel->getUserCode($id);
//        $code = trim($code, ',');
//        $this->assign([
//            'lists' => $lists,
//            'code' => $code,
//            'id' => $id
//        ]);
//        return $this->fetch('uuser/editusercode');
//    }
    
    /**
     * 审核
     * @return mixed
     */
    public function uUserAttestation(){
        if(Request::instance()->isAjax()){
            $params = input('param.');
            $uUserModel = new UUserModel();
            $mechanismModel = new MechanismModel();
            $is_zyx = '';
            if($params['user_attestation'] == 4){//驳回
                $num = '';//无志愿者编号
            }else{//通过，这需要志愿者编号
                $num = $uUserModel->getMaxNum($params['mechanism_id']);
                $res = $mechanismModel->getMechanismCode($params['mechanism_id']);
                $mechanism_code = trim($res['mechanism_code'], ',');
                //志愿者编号
                if(!$num){//该机构暂无志愿者
                    $num = ',' . $mechanism_code . '00001' . ',';
                }else{
                    $num = trim($num, ',') + 1;
                    $leng = strlen($num);
                    $totalLeng = '';
                    if($res['mechanism_type'] == 1){
                        $totalLeng = 8;
                    }elseif($res['mechanism_type'] == 2){
                        $totalLeng = 11;
                    }elseif($res['mechanism_type'] == 3){
                        $totalLeng = 14;
                    }elseif($res['mechanism_type'] == 4){
                        $totalLeng = 17;
                    }elseif($res['mechanism_type'] == 5){
                        $totalLeng = 20;
                    }
                    $zero = '';
                    if($leng < $totalLeng){
                        for($i=$leng; $i<$totalLeng; $i++){
                            $zero .= '0';
                        }
                    }
                    $num = ',' . $zero . $num . ',';
                }
                $params['user_false_reason'] = null;//驳回原因为空
                $is_zyx = 1;
            }
            
            $data = [
                'user_attestation' => $params['user_attestation'],//审核状态
                'user_number' => $num,//志愿者编号
                'user_false_reason' => $params['user_false_reason'],//驳回原因
                'user_sh_time' => date('Y-m-d H:i:s'),//审核通过时间
                'is_zyx' => $is_zyx,//志愿者之星
            ];
            $res = $uUserModel->updateCode($params['user_id'], $data);
            $phone = Db::table('up_u_user')->where('user_id', $params['user_id'])->value('user_phone');
            if($res){
                $list = [];
                if($params['user_attestation'] == 3){
                    //TODO:审核通过发送短信&推送
                    $uid = (string)$params['user_id'];
                    array_push($list, $uid);
                    $templateid = config('yzx')['pass'];
                    try{
                        $this->Jpush(1, $list, '审核结果通知', ['type'=>1], '您的志愿者申请已通过', 3);
                    }catch(\Exception $e){
                        
                    }
                    try{
                        YzxSms($templateid, '', $phone, $params['user_id']);//发送短信
                    }catch(\Exception $e){
                        
                    }
                }else{
                    //TODO:驳回发送短信&推送
                    $uid = (string)$params['user_id'];
                    array_push($list, $uid);
                    $templateid = config('yzx')['reject'];
                    try{
                        $this->Jpush(1, $list, '审核结果通知', ['type'=>1], '您的志愿者申请未通过，点击查看详情', 3);
                    }catch(\Exception $e){
                        
                    }
                    try{
                        YzxSms($templateid, '', $phone, $params['user_id']);//发送短信
                    }catch(\Exception $e){
        
                    }
                }
                return json(['code' => 200, 'data' => '', 'msg' => '审核成功']);
            }else{
                return json(['code' => 100, 'data' => '', 'msg' => '审核失败']);
            }
        }
        $user_id = input('param.id');
        $field = 'uuu.user_rel_name, uuu.user_card, um.mechanism_name, ua.district, ua1.assortment_name as user_hospital, 
        ua2.assortment_name as user_department, ua3.assortment_name as user_title, ua4.assortment_name as user_post, 
        uuu.user_business_image, um.mechanism_id, uuu.user_id';
        $uUserModel = new UUserModel();
        $info = $uUserModel->getAttestation($user_id, $field);
        $info['user_business_image'] = explode(',', trim($info['user_business_image'], ','));
        $this->assign('info', $info);
        return $this->fetch('uuser/uuserattestation');
    }
    
    /**
     * 详情
     * @return mixed
     */
    public function uUserInfo(){
        $user_id = input('param.id');
        $field = 'uuu.user_rel_name, uuu.user_card, um.mechanism_name, ua.district, ua1.assortment_name as user_hospital, 
        ua2.assortment_name as user_department, ua3.assortment_name as user_title, ua4.assortment_name as user_post, 
        uuu.user_business_image, uuu.user_attestation, uuu.user_false_reason';
        $uUserModel = new UUserModel();
        $info = $uUserModel->getAttestation($user_id, $field);
        $info['user_business_image'] = explode(',', trim($info['user_business_image'],','));
        $this->assign('info', $info);
        return $this->fetch('uuser/uuserinfo');
    }
    
    /**
     * 停用/启用用户
     * @return \think\response\Json
     */
//    public function uUserStatus(){
//        $params = input('param.');
//        $uUserModel = new UUserModel();
//        $res = $uUserModel->uUserStatus($params['num'], $params['id']);
//        return json(['code' => $res['code'], 'data' => $res['data'], 'msg' => $res['msg']]);
//    }
    
    /**
     * checkPhone 验证手机号的合法性
     */
    public function checkPhone(){
        $params = input('param.');
        if(!preg_match("/^1[345678]{1}\d{9}$/",$params['mechanism_member_phone'])){
            echo "false";
        }else{
            echo "true";
        }
    }

    

    
    
}